from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import TimeoutException
import datetime
import json
import redis

r = redis.Redis('localhost', port=6379, db=1, decode_responses=True)

# 订单链接
order_url = 'https://pcashier.jd.com/cashier/index.action?orderId=83332719067&reqInfo=eyJ2ZXJzaW9uIjoiMy4wIiwib3JkZXJJZCI6IjgzMzMyNzE5MDY3IiwicGF5QW1vdW50IjoiMzM4My41OCIsIm9yZGVyQW1vdW50IjoiMzM4My41OCIsImNvbXBhbnlJZCI6IjYwMCIsIm9yZGVyVHlwZSI6IjAiLCJ0b1R5cGUiOiIxMCIsImNhdGVnb3J5IjoiMSJ9&sign=d2046f24c305aeb4d2e3dd4409d031c9'
# 选择银行
pay_name = '中国银行'


class Jd(object):
    # 初始化参数
    def __init__(self):
        options = webdriver.ChromeOptions()
        # if r.get('jd') is not None:
        #     options.add_argument('--headless')
        self.browser = webdriver.Chrome(options=options)
        self.wait = WebDriverWait(self.browser, 10)

    # cookies登陆
    def login(self):
        print('用户登陆...')
        if r.get('jd') is None:
            raise 'redis cookies not find'

        listCookies = json.loads(r.get('jd'))
        self.browser.get('https://passport.jd.com/new/login.aspx')
        self.browser.delete_all_cookies()

        for cookie in listCookies:
            self.browser.add_cookie(cookie)

    # 扫码登陆获取用户cookies info
    def scan_login(self):
        print('扫码获取用户cookies')
        self.browser.get('https://passport.jd.com/new/login.aspx')
        while True:
            try:
                self.wait.until(
                    EC.text_to_be_present_in_element((
                        By.CSS_SELECTOR,
                        '#shortcut > div > ul.fr > li.shortcut_btn.fore2 > div > a'
                    ), '我的订单'))
                r.set('jd', json.dumps(self.browser.get_cookies()))
                break
            except TimeoutException:
                print('继续等待扫码获取')

    # 是否验证条件，等待出现指定价格, 出现后跳出循环
    def checkout_select(self):
        num = 0
        while True:
            try:
                self.wait.until(
                    EC.presence_of_element_located((
                        By.CSS_SELECTOR,
                        '#payChannelListId > div:nth-child(5) > div > div:nth-child(6) > a'
                    )))

                price = self.browser.find_element_by_xpath(
                    '//b[contains(text(),"300")]')
                if price:
                    print('找到了300块,支付中')
                    break
            except NoSuchElementException:
                self.browser.refresh()
                num += 1
                print('没有找到,尝试刷新页面, 次数:{}'.format(num))

    # 收银台支付
    def checkstand(self, is_checkout=False):
        assert '收银台' in self.browser.title, '没有成功进入收银台'
        if is_checkout:
            self.checkout_select()

        # 选择银行
        self.wait.until(
            EC.presence_of_element_located(
                (By.XPATH, '//strong[text()="{}"]'.format(pay_name)))).click()

        # 输入支付密码
        self.wait.until(
            EC.presence_of_element_located((
                By.CSS_SELECTOR,
                '#payChannelListId > div:nth-child(5) > div > div.pv-line.pv-line-shortPwd > span > input:nth-child(1)'
            ))).send_keys('472323')

        # 确认支付
        self.wait.until(
            EC.presence_of_element_located((
                By.CSS_SELECTOR,
                '#payChannelListId > div:nth-child(5) > div > div:nth-child(6) > a'
            ))).click()

        # 验证是否成功
        try:
            self.wait.until(
                EC.text_to_be_present_in_element((
                    By.CSS_SELECTOR,
                    '#resultArea > div.porm-result-area.clearfix > div.pay-result-infor-box > div.result-infor-con > p:nth-child(2)'
                ), '购买成功'))
            print('完成支付成功')
        except NoSuchElementException:
            print('未完成，其它返回异常')

    # 抢购订单
    def pay_shop(self):
        # 打开订单
        self.browser.get(order_url)
        # 进入收银台
        self.checkstand()

    def run(self):
        if r.get('jd') is None:
            self.scan_login()
        self.login()

        start_time = datetime.datetime(2019, 1, 24, 16, 59, 58)
        print('任务时间: {}'.format(start_time.strftime('%Y-%m-%d %H:%M:%S')))

        while True:
            if datetime.datetime.today() >= start_time:
                print('时间到了')
                self.pay_shop()
                break


# 运行
Jd().run()
